﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using System.Runtime.Remoting;

namespace RDPServer.Tool
{
    public partial class frmChat : Form
    {
        static Rectangle m_Loc;
        public static ArrayList m_Msg = new ArrayList();

        public frmChat()
        {
            InitializeComponent();
            FillActiveUsers();
            RDPRemoteObject.FaxBusiness.FaxSendedEvent += new RDPCommon.FaxEventHandler(OnFaxSended);                        
            RDPRemoteObject.UserLogin.UserLoginEvent += new RDPCommon.UserLoginEventHandler(OnUserLogin);
            RDPRemoteObject.UserLogin.UserLogoutEvent += new RDPCommon.UserLogoutEventHandler(OnUserLogout);
        }
        
        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                ArrayList al = new ArrayList();
                foreach (TreeNode tn in this.treeView1.Nodes)
                {
                    if (tn.Checked)
                        al.Add((tn.Tag as RDPCommon.Client.ClinetInfo).SessionID);
                }
                if (al.Count == 0)
                {                    
                    RDPCommon.Util.ShowWarningDialog("请至少选择一项接收客户端.");
                    return;
                }

                if (String.IsNullOrEmpty(this.textBox1.Text))
                {
                    RDPCommon.Util.ShowWarningDialog("发送信息不可为空.");
                    this.textBox1.Focus();
                    return;
                }
                string msg = "";
                msg = System.DateTime.Now.ToString("yyyy-MM-dd hh:MM:ss") + " (" + RDPCommon.Util.GetIpAddress() + " 服务端)";
                msg += System.Environment.NewLine;                
                msg += this.textBox1.Text.Trim();
                msg += System.Environment.NewLine;
                msg += System.Environment.NewLine;      
                object[] rtn = RDPCommon.Server.ServerTool.BroadCastingInfo(
                    new object[] { al.ToArray(), msg });
                if (rtn != null && Convert.ToInt32(rtn[0]) != 0)
                {
                    Exception ex = rtn[1] as Exception;
                    throw ex;
                }
                else
                {
                    SetMessage(1, msg);
                    this.textBox1.Focus();
                    this.textBox1.Text = "";                    
                }
            }
            catch (Exception ex)
            {                                
                RDPCommon.Util.ShowExceptionDialog(ex);
            }
        }

        public void OnFaxSended(string msg)
        {
            if (frm == null)
                return;
            if (this.textBox2.InvokeRequired)
            {
                this.textBox2.Invoke(new SetMsgHandler(SetMessage),new object[]{0, msg});
            }
            else
            {
                SetMessage(0,msg);
            }
        }

        delegate void SetMsgHandler(int flag, string msg);

        void SetMessage(int flag,string msg) //0 接收的消息 1 发出的消息
        {
            msg = msg.Replace(System.Environment.NewLine, "<br>");
            if (flag==0)
                this.textBox2.DocumentText += "<div style='color:red;'>" + msg + "</div>";
            else if (flag ==1)
                this.textBox2.DocumentText += "<div style='color:blue;'>"+msg+"</div>";
            this.Activate();
        }

        static frmChat frm = null;
        /// <summary>
        /// 
        /// </summary>
        /// <param name="parent">父窗体，可为null</param>
        public static void ShowChat(Form parent, Rectangle loc)
        {
            frmChat.m_Loc = loc;
            if (frm == null)
            {
                frm = new frmChat();
                if (parent != null)
                {
                    frm.Owner = parent;                    
                }
                InitMessage();
            }
            if (frm.WindowState == FormWindowState.Minimized)
                frm.WindowState = FormWindowState.Normal;
            SetLocation();
            frm.Show();            
            frm.Activate();
        }

        static void InitMessage()
        {
            StringBuilder sb = new StringBuilder();
            foreach (string s in frmChat.m_Msg)
                sb.Append(s);
            frm.SetMessage(0, sb.ToString());
        }

        static void SetLocation()
        {
            frm.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
        }

        void FillActiveUsers()
        {
            this.treeView1.Nodes.Clear();
            Dictionary<string, RDPCommon.Client.ClinetInfo> dic = RDPRemoteObject.UserLogin.GetActiveUsers();
            TreeNode tn;
            foreach (KeyValuePair<string,RDPCommon.Client.ClinetInfo> kp in dic)
            {
                tn = new TreeNode(kp.Value.UserCode);
                tn.Name = kp.Value.SessionID;
                tn.Tag = kp.Value;                
                this.treeView1.Nodes.Add(tn);
            }
        }

        public void OnUserLogin(RDPCommon.Client.ClinetInfo clientInfo)
        {
            if (this.treeView1.InvokeRequired)
            {
                this.treeView1.Invoke(new UpdateTreeDelegate(UpdateTree), new object[] { 0, clientInfo });
            }
            else
            {
                UpdateTree(0, clientInfo);
            }
        }

        public void OnUserLogout(RDPCommon.Client.ClinetInfo clientInfo)
        {
            if (frm == null)
                return;
            if (this.treeView1.InvokeRequired)
            {
                this.treeView1.Invoke(new UpdateTreeDelegate(UpdateTree), new object[] { 1, clientInfo });
            }
            else
            {
                UpdateTree(1, clientInfo);
            }
        }

        delegate void UpdateTreeDelegate(int flag, RDPCommon.Client.ClinetInfo clientInfo);

        void UpdateTree(int flag, RDPCommon.Client.ClinetInfo clientInfo) //0 Add 1 Remove
        {
            //当窗体已关闭,但收到用户登录或注销的通知时,不处理,否则出错
            if (frm == null)
                return;
            TreeNode tn = null;
            if (flag == 0)
            {
                tn = new TreeNode(clientInfo.UserCode);
                tn.Name = clientInfo.SessionID;
                tn.Tag = clientInfo;                
                this.treeView1.Nodes.Add(tn);
            }
            else if (flag == 1)
            {
                TreeNode[] tns = this.treeView1.Nodes.Find(clientInfo.SessionID,true);
                if (tns.Length  > 0)
                    this.treeView1.Nodes.Remove(tns[0]);
            }
        }

         private void frmChat_FormClosed(object sender, FormClosedEventArgs e)
         {
             RDPRemoteObject.FaxBusiness.FaxSendedEvent -= new RDPCommon.FaxEventHandler(OnFaxSended);  
             RDPRemoteObject.UserLogin.UserLoginEvent -= new RDPCommon.UserLoginEventHandler(OnUserLogin);
             RDPRemoteObject.UserLogin.UserLogoutEvent -= new RDPCommon.UserLogoutEventHandler(OnUserLogout);
             frm = null;
         }

         private void checkBox1_CheckedChanged(object sender, EventArgs e)
         {
             CheckBox ckb = sender as CheckBox;
             foreach (TreeNode tn in this.treeView1.Nodes)
             {
                 tn.Checked = ckb.Checked;
             }
         }

         private void textBox2_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
         {
             this.textBox2.Document.Window.Parent.ScrollTo(0, System.Int32.MaxValue);   
         }

         bool CtrlDown = false;
         private void textBox1_KeyDown(object sender, KeyEventArgs e)
         {
             if (e.Control && e.KeyCode == Keys.Enter)
             {
                 CtrlDown = true;
                 button1_Click(null, null);
             }
         }

         private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
         {
             if (CtrlDown)
                 e.Handled = true;
         }

         private void textBox1_KeyUp(object sender, KeyEventArgs e)
         {
             CtrlDown = e.Control;
         }            
    }
}
